package cn.zh.npro.Activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.Nullable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.zh.npro.Adapter.CeAdapter;
import cn.zh.npro.Adapter.CpAdapter;
import cn.zh.npro.Adapter.CrAdapter;
import cn.zh.npro.Adapter.CtAdapter;
import cn.zh.npro.Item.ACItem;
import cn.zh.npro.Item.AcLItem;
import cn.zh.npro.Item.ClevItem;
import cn.zh.npro.Item.CpItem;
import cn.zh.npro.Item.CrItem;
import cn.zh.npro.Item.CtItem;
import cn.zh.npro.Item.CustItem;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;
import cn.zh.npro.Util.BaseUrl;
import cn.zh.npro.Util.Loading;
import cn.zh.npro.Util.ToastUtil;
import cn.zh.npro.citythreelist.ProvinceActivity;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class AddClient extends BaseActivity {
    ImageView ad_back;
    LinearLayout clvelin,claslin,ptlin,adrelin;

    PopupWindow popupWindow;
    CeAdapter ceAdapter;
    ArrayList<ClevItem> clevItems=new ArrayList<>();
    CtAdapter ctAdapter;
    ArrayList<CtItem> ctItems=new ArrayList<>();
    CpAdapter cpAdapter;
    CrAdapter crAdapter;
    ArrayList<CpItem> cpItems=new ArrayList<>();
    ArrayList<CrItem> crItems =new ArrayList<>();
    int type=0;
    ClevItem clevItem=null;
    CtItem ctItem=null;
    CpItem cpItem=null;
    CrItem crItem=null;
    TextView cuslevel,custype,paytype,cadress;

    EditText edtadress,ecliname;
    MyApplication mapp;
    LinearLayout setlink;
    ArrayList<AcLItem> acLItems=null;
    TextView lmtxt,adcom;

    String handleName,handle;

    String provinceId="",cityId="",countyId="",provinceName="",cityName="",countyName="";

    private Dialog LDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_client);
        mapp= (MyApplication) getApplication();
        handleName=mapp.getSp().getString("Linkman","");
        handle=mapp.getSp().getString("uid","");
        initad();

    }

    @Override
    protected void onResume() {
        super.onResume();
        acLItems=mapp.getMacLItems();
        if (acLItems.size()==0){
            lmtxt.setText("未设置");
        }else {
            lmtxt.setText("已设置");
        }
        if (mapp.isIscity()){
            provinceName=mapp.getProviece().getName();
            cityName=mapp.getCityitem().getName();
            countyName=mapp.getAreaim().getName();
            provinceId=mapp.getProviece().getId();
            cityId=mapp.getCityitem().getId();
            countyId=mapp.getAreaim().getId();
            cadress.setText(provinceName+"-"+cityName+"-"+countyName);
            mapp.setIscity(false);
        }
    }


    public void initad(){
        ad_back=findViewById(R.id.ad_back);
        clvelin=findViewById(R.id.clvelin);
        claslin=findViewById(R.id.claslin);
        cuslevel=findViewById(R.id.cuslevel);
        custype=findViewById(R.id.custype);
        paytype=findViewById(R.id.paytype);
        cadress=findViewById(R.id.cadress);
        edtadress=findViewById(R.id.edtadress);
        ecliname=findViewById(R.id.ecliname);

        ptlin=findViewById(R.id.ptlin);
        adrelin=findViewById(R.id.adrelin);

        setlink=findViewById(R.id.setlink);
        lmtxt=findViewById(R.id.lmtxt);

        adcom=findViewById(R.id.adcom);
        ad_back.setOnClickListener(this);
        setlink.setOnClickListener(this);
        adcom.setOnClickListener(this);

        clvelin.setOnClickListener(this);
        claslin.setOnClickListener(this);
        ptlin.setOnClickListener(this);
        adrelin.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        int id=view.getId();
        switch (id){
            case R.id.ad_back:
                finish();
                break;
            case R.id.clvelin:
                type=0;
                showPopUp();
                initcls();
                break;
            case R.id.claslin:
                type=1;
                showPopUp();
                getGetCustomerClass();
                break;
            case R.id.ptlin:
                type=2;
                showPopUp();
                Chatype();
                break;
            case R.id.adrelin:
                cadress.setText("");
                mapp.setArechose(1);
                //地址
                Intent intent=new Intent(AddClient.this, ProvinceActivity.class);
                startActivity(intent);
                break;
            case R.id.setlink:
                Intent intent1=new Intent(AddClient.this,AcLink.class);
                startActivity(intent1);
                break;
            case R.id.adcom:
                LDialog= Loading.createLoadingDialog(this,"加载中...");
                String daress=edtadress.getText().toString();
                String eclina=ecliname.getText().toString();
                String copan=custype.getText().toString();
                String colev=cuslevel.getText().toString();
                String pttxt=paytype.getText().toString();
                if (eclina.equals("")){
                    ToastUtil.showLong(AddClient.this,"客户名称未填写");
                    Loading.closeDialog(LDialog);
                    return;
                }
                if (colev.equals("")){
                    ToastUtil.showLong(AddClient.this,"请设置客户级别");
                    Loading.closeDialog(LDialog);
                    return;
                }
                if (copan.equals("")){
                    ToastUtil.showLong(AddClient.this,"请设置客户分类");
                    Loading.closeDialog(LDialog);
                    return;
                }
                if (pttxt.equals("")){
                    ToastUtil.showLong(AddClient.this,"请设置付款方式");
                    Loading.closeDialog(LDialog);
                    return;
                }

                if (daress.equals("")){
                    ToastUtil.showLong(AddClient.this,"请填写详细地址");
                    Loading.closeDialog(LDialog);
                    return;
                }

                CustItem custItem=new CustItem(handleName,provinceName,handle,countyId,daress,cityName,eclina,countyName,provinceId,copan,cityId,colev,pttxt);
                ACItem acItem=new ACItem(custItem,acLItems);
                Gson gson=new Gson();
                String str=gson.toJson(acItem);
                getadPost(str);
                break;
        }
    }


    //侧滑弹窗
    private void showPopUp() {
        View vp = LayoutInflater.from(AddClient.this).inflate(R.layout.clv_layout, null, false);
        ListView lplist=vp.findViewById(R.id.plist);
        TextView ptitle=vp.findViewById(R.id.ptitle);
        switch (type){
            case 0:
                ptitle.setText("客户级别");
                String txt=cuslevel.getText().toString();
                ceAdapter = new CeAdapter(AddClient.this,clevItems,txt);
                lplist.setAdapter(ceAdapter);
                break;
            case 1:
                ptitle.setText("客户分类");
                String txt1=custype.getText().toString();
                crAdapter = new CrAdapter(AddClient.this,crItems,txt1);
                lplist.setAdapter(crAdapter);
                break;
            case 2:
                ptitle.setText("付款方式");
                String txt2=paytype.getText().toString();
                cpAdapter = new CpAdapter(AddClient.this,cpItems,txt2);
                lplist.setAdapter(cpAdapter);
                break;
        }

        lplist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (type){
                    case 0:
                        popupWindow.dismiss();
                        cuslevel.setText(clevItems.get(i).getCustomerLevelTitle());
                        clevItem=clevItems.get(i);
                        break;
                    case 1:
                        popupWindow.dismiss();
                        custype.setText(crItems.get(i).getClassName());
                        crItem=crItems.get(i);
                        break;
                    case 2:
                        popupWindow.dismiss();
                        paytype.setText(cpItems.get(i).getChargeTypeName());
                        cpItem=cpItems.get(i);
                        break;
                }
            }
        });

        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int  mScreenWitdh = outMetrics.widthPixels;
        popupWindow = new PopupWindow(vp, mScreenWitdh-200, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.GRAY));
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        popupWindow.setClippingEnabled(false);
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha=0.5f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp =getWindow().getAttributes();
                lp.alpha=1.0f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindow.showAtLocation(findViewById(R.id.activity_add_client), Gravity.NO_GRAVITY, 200, 0);
    }


    public void initcls(){
        OkHttpUtils.get(BaseUrl.GetCustomerLevel)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State){
                                JSONArray Res=js.getJSONArray("Res");
                                clevItems.clear();
                                for (int i=0;i<Res.length();i++){
                                    JSONObject ji=Res.getJSONObject(i);
                                    String customerLevelId=ji.getString("customerLevelId");
                                    String customerLevel=ji.getString("customerLevel");
                                    String customerLevelTitle=ji.getString("customerLevelTitle");
                                    String days=ji.getString("days");
                                    String sortOrder=ji.getString("sortOrder");
                                    ClevItem clevItem=new ClevItem(customerLevelId,customerLevel,customerLevelTitle,days,sortOrder);
                                    clevItems.add(clevItem);

                                }
                                ceAdapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }



    public void getGetCustomerClass(){
        OkHttpUtils.get(BaseUrl.GetCustomerClass)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State) {
                                JSONArray Res = js.getJSONArray("Res");
                                crItems.clear();
                                for (int i = 0; i < Res.length(); i++) {
                                    JSONObject ji = Res.getJSONObject(i);
                                    String ClassID = ji.getString("ClassID");
                                    String ClassName = ji.getString("ClassName");
                                    String OrderPos = ji.getString("OrderPos");
                                    String bBlockUp = ji.getString("bBlockUp");
                                    CrItem crItem = new CrItem(ClassID, ClassName, OrderPos, bBlockUp);
                                    crItems.add(crItem);
                                }
                                crAdapter.notifyDataSetChanged();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }





    public void Chatype(){
        OkHttpUtils.get(BaseUrl.GetChargeType)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            if (State) {
                                JSONArray Res = js.getJSONArray("Res");
                                cpItems.clear();
                                for (int i = 0; i < Res.length(); i++) {
                                    JSONObject ji = Res.getJSONObject(i);
                                    String ChargeTypeID = ji.getString("ChargeTypeID");
                                    String ChargeTypeName = ji.getString("ChargeTypeName");
                                    String OrderPos = ji.getString("OrderPos");
                                    String bBlockUp = ji.getString("bBlockUp");
                                    CpItem cpItem = new CpItem(ChargeTypeID, ChargeTypeName, OrderPos, bBlockUp);
                                    cpItems.add(cpItem);
                                }
                                cpAdapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }




    public void getadPost(String str){
        OkHttpUtils.post(BaseUrl.AddCustomer)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        Loading.closeDialog(LDialog);
                        System.out.println("--------->添加客户==="+s);
                        try {
                            JSONObject js=new JSONObject(s);
                            boolean State=js.getBoolean("State");
                            String Msg=js.getString("Msg");
                            ToastUtil.showLong(AddClient.this,Msg);
                            if (State){
                                finish();
                            }
                        }catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }


}
